﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.Configuration;
namespace Peer.Web
{
    public static class Cookies
    {
        static Cookies()
        {
            Initialize();
        }
        private static bool IsInitialized = false;
        private static CookiesProvider _provider;
        public static CookiesProvider Provider
        {
            get
            {
                return _provider;
            }
        }
        private static CookiesProviderCollection _providers;
        public static CookiesProviderCollection Providers
        {
            get
            {
                return _providers;
            }
        }
        private static void Initialize()
        {
            string providerType;
            string assemblyName;
            CookiesProvider tprovider;
            Assembly myAssembly;
            if (IsInitialized)
                return;
            CookiesProviderSection sec = (CookiesProviderSection)ConfigurationManager.GetSection("Cookies");
            _providers = new CookiesProviderCollection();
            foreach(ProviderSettings settings in sec.Providers)
            {
                providerType=settings.Type.Trim().Split(new char[]{','})[0];
                assemblyName= settings.Type.Trim().Remove(settings.Type.IndexOf(providerType), providerType.Length);
                if(string.IsNullOrEmpty(assemblyName))
                    myAssembly=Assembly.GetExecutingAssembly();
                else
                {
                    assemblyName=assemblyName.Trim().Remove(0,1);
                    myAssembly=Assembly.Load(assemblyName);
                }
                tprovider=(CookiesProvider)myAssembly.CreateInstance(providerType);
                tprovider.Initialize(settings.Name,settings.Parameters);
                _providers.Add(tprovider);
            }
            if(!string.IsNullOrEmpty(sec.DefaultProvider))
            {
                _provider=_providers[sec.DefaultProvider];
            }
            else
            {
                _provider=_providers[sec.Providers[0].Name];
            }
            IsInitialized=true;
        }
    }
}
